package com.ruoyi.pos.api.service.task.impl;

import com.ruoyi.common.enums.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pos.api.dto.user.UserTeamDto;
import com.ruoyi.pos.api.service.common.ICommonService;
import com.ruoyi.pos.api.service.task.IOrderTaskService;
import com.ruoyi.pos.api.utils.CommonUtils;
import com.ruoyi.pos.api.vo.user.UserTeamListVo;
import com.ruoyi.pos.web.domain.*;
import com.ruoyi.pos.web.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author luobo
 * @title: OrderTaskServiceImpl
 * @projectName pos
 * @description: TODO
 * @date 2021-11-08 11:43:32
 */
@Service
public class OrderTaskServiceImpl implements IOrderTaskService {
    private static final Logger log = LoggerFactory.getLogger(OrderTaskServiceImpl.class);
    @Autowired
    private TUserInfoMapper userInfoMapper;
    @Autowired
    private TUserTeamInfoMapper userTeamInfoMapper;
    @Autowired
    private TUserDefaultInfoMapper userDefaultInfoMapper;
    @Autowired
    private TGradeInfoMapper gradeInfoMapper;
    @Autowired
    private TOrderInfoMapper orderInfoMapper;
    @Autowired
    private TOrderSnInfoMapper orderSnInfoMapper;
    @Autowired
    private TTerminalInfoMapper terminalInfoMapper;
    @Autowired
    private TStatisticInfoMapper statisticInfoMapper;
    @Autowired
    private ICommonService commonService;
    @Autowired
    private CommonUtils commonUtils;

    //查询需要自动取消的订单
    @Override
    public List<TOrderInfo> queryCloseTimeoutOrders() throws Exception {

        //select * from  t_order_info t where (select count(1) as num from t_order_worker_info w where t.order_id = w.order_id and w.user_state in ('0', '1')) = 0 ;
        TRebateSetInfo rebateSetInfo = commonService.queryTRebateSetInfoVo();
        String waitCancelTime = rebateSetInfo.getWaitCancelTime();
        String waitConfirmTime = rebateSetInfo.getWaitConfirmTime();
        //1、查询出所有需要关闭的工单记录
        List<TOrderInfo> orderList = orderInfoMapper.queryCloseTimeoutOrders(waitCancelTime, waitConfirmTime);
        return orderList;
    }

    //自动关单
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void closeTimeoutOrders(String orderId) throws Exception {
        TOrderInfo order = orderInfoMapper.selectTOrderInfoById(orderId); //重新查询订单判断最新状态，防止并发操作
        if (OrderStatusEnums.TIMEOUT_CLOSE.getCode().equals(order.getOrderStatus())) {
            log.info("该订单已关闭，不能再操作，数据主键orderId：" + orderId);
            return;
        }
        if (OrderStatusEnums.WAIT_PAY.getCode().equals(order.getOrderStatus())) { //超时未支付，自动取消订单
            order.setOrderStatus(OrderStatusEnums.TIMEOUT_CLOSE.getCode());
        } else if (OrderStatusEnums.HAS_RECEIPT.getCode().equals(order.getOrderStatus())) { //超时未确认收货
            order.setOrderStatus(OrderStatusEnums.HAS_OVER.getCode());
            orderInfoMapper.updateTOrderInfo(order);
            TUserInfo user = userInfoMapper.selectTUserInfoByUserId(order.getUserId());

            //计算终端数
            TOrderSnInfo mapper = new TOrderSnInfo();
            mapper.setOrderId(order.getId());
            List<TOrderSnInfo> snList = orderSnInfoMapper.selectTOrderSnInfoList(mapper);
            Optional.ofNullable(snList).ifPresent(sns ->{
                sns.stream().forEach(sn ->{
                    TTerminalInfo terminal = terminalInfoMapper.selectTTerminalInfoBySnCode(sn.getSnCode());
                    TStatisticInfo statistic = statisticInfoMapper.selectTStatisticInfoForCurrentDay(order.getUserId(), terminal.getBrandId());
                    if (null == statistic) {
                        statistic = commonUtils.generateStatisticInfo(user, DateUtils.getNowDate(), terminal.getBrandId());
                        statisticInfoMapper.insertTStatisticInfo(statistic);
                    }
                    statistic.setMyTerminalNum(statistic.getMyBuyTerminalNum().add(BigDecimal.ONE)); //计算终端数
                    if (OrderTypeEnum.TERMINALPURCHASE.getCode().equals(order.getOrderType())) {
                        statistic.setMyBuyTerminalNum(statistic.getMyBuyTerminalNum().add(BigDecimal.ONE)); //计算购买终端数
                        terminal.setTerminalType(TerminalTypeEnum.BUY.getCode());
                    } else {
                        statistic.setMyExchangelTerminalNum(statistic.getMyExchangelTerminalNum().add(BigDecimal.ONE)); //计算兑换终端数
                        terminal.setTerminalType(TerminalTypeEnum.EXCHSNGE.getCode());
                    }
                    if (null != terminal.getTerminalGmv() && terminal.getTerminalGmv().compareTo(BigDecimal.ZERO) > 0) { //说明已经有交易额，计算我的交易额
                        statistic.setMyTransMoney(statistic.getMyTransMoney().add(terminal.getTerminalGmv()));
                    }
                    statisticInfoMapper.updateTStatisticInfo(statistic);
                    terminal.setUserId(order.getUserId());
                    terminal.setUserName(user.getUserName());
                    terminal.setPhone(user.getUserPhone());
                    terminal.setTransStatus(TransStatusEnum.WAIT_TRANS.getCode());
                    terminalInfoMapper.updateTTerminalInfo(terminal);
                });
            });

            if (OrderTypeEnum.TERMINALPURCHASE.getCode().equals(order.getOrderType())) { //购买的，发放采购奖励，直接发放到余额
                log.info("-----------------购买终端确认收货，产生采购收益------------------上级用户：" + user.getSuperiorUserId());
                List<TGradeInfo> gradeList = gradeInfoMapper.selectTGradeInfoList(new TGradeInfo())
                        .stream()
                        .sorted(Comparator.comparing(TGradeInfo::getSort).reversed())
                        .collect(Collectors.toList());
                TGradeInfo gradeMax = gradeList.stream().max(Comparator.comparing(TGradeInfo::getSort)).get();
                TRebateSetInfo set = commonService.queryTRebateSetInfoVo();
                //计算采购收益（直属上级）、purchasing_rebate
                BigDecimal purchasingRebate = order.getPayAmount().multiply(set.getPurchasingRebate()); //采购收益
                BigDecimal workSubsidy = order.getPayAmount().multiply(set.getWorkSubsidy()); //办公补贴
                if (gradeMax.getId().equals(user.getGradeId())) { //核心V9产生的采购奖励、办公补贴由自己获取
                    log.info("-----------------购买终端确认收货，产生采购收益------------------采购收益分润金额：" + purchasingRebate + ",采购收益人" + user.getUserId());
                    user.setBalanceSum(user.getBalanceSum().add(purchasingRebate));
                    TUserDefaultInfo defaultInfo = commonUtils.generateTUserDefaultInfo(
                            user.getUserId(),
                            order.getBrandId(),
                            TransTypeEnum.YUE.getCode(),
                            TransOperTypeEnum.YUE_1007.getCode(),
                            purchasingRebate,
                            order.getId(),
                            order.getUserId(),
                            null,
                            "",
                            null);
                    userDefaultInfoMapper.insertTUserDefaultInfo(defaultInfo);

                    log.info("-----------------购买终端确认收货，核心V9自己产生采购收益------------------采购收益分润金额：" + purchasingRebate);
                    user.setBalanceSum(user.getBalanceSum().add(workSubsidy));
                    userInfoMapper.updateTUserInfo(user);
                    TUserDefaultInfo defaultInfoWork = commonUtils.generateTUserDefaultInfo(
                            user.getUserId(),
                            order.getBrandId(),
                            TransTypeEnum.YUE.getCode(),
                            TransOperTypeEnum.YUE_1009.getCode(),
                            workSubsidy,
                            order.getId(),
                            order.getUserId(),
                            null,
                            "",
                            null);
                    userDefaultInfoMapper.insertTUserDefaultInfo(defaultInfoWork);
                } else { //其他情况都由上级获取
                    TUserInfo supUser = userInfoMapper.selectTUserInfoByUserId(user.getSuperiorUserId());
                    supUser.setBalanceSum(supUser.getBalanceSum().add(purchasingRebate));
                    userInfoMapper.updateTUserInfo(supUser);
                    log.info("-----------------购买终端确认收货，产生采购收益------------------采购收益分润金额：" + purchasingRebate + ",采购收益人" + supUser.getUserId());
                    TUserDefaultInfo defaultInfo = commonUtils.generateTUserDefaultInfo(
                            supUser.getUserId(),
                            order.getBrandId(),
                            TransTypeEnum.YUE.getCode(),
                            TransOperTypeEnum.YUE_1007.getCode(),
                            purchasingRebate,
                            order.getId(),
                            order.getUserId(),
                            null,
                            "",
                            null);
                    userDefaultInfoMapper.insertTUserDefaultInfo(defaultInfo);
                    //计算办公补贴（跨级分润）、work_subsidy

                    /*for (TGradeInfo g : gradeList) {
                        System.out.println(g.getId() + "------------------sort:-------------"+g.getSort());
                    }*/
                    UserTeamDto teamMapper = new UserTeamDto();
                    teamMapper.setUserId(user.getUserId());
                    List<UserTeamListVo> teamList = userTeamInfoMapper.selectUserTeamListForParent(teamMapper); //查询本人所在的团队，且会员等级高于本人的上级用户列表
                    log.info("-----------------购买终端确认收货，产生办公补贴------------------最高的会员等级id：" + gradeList.get(0).getId());
                    /*for (UserTeamListVo g : teamList) {
                        System.out.println(g.getUserId() + "------------------自己的上级用户:-------------" + g.getGradeId() + "=============" + gradeList.get(0).getId().equals(g.getGradeId()));
                    }*/
                    List<String> supTeamList = teamList.stream()
                            .filter(bean ->gradeList.get(0).getId().equals(bean.getGradeId()))
                            .map(UserTeamListVo::getUserId)
                            .distinct()
                            .collect(Collectors.toList());
                    log.info("-----------------购买终端确认收货，产生办公补贴------------------最高的会员等级id：" + supTeamList);
                    //上级核心V9获取办公补贴
                    log.info("-----------------购买终端确认收货，产生办公补贴------------------办公补贴分润金额：" + purchasingRebate);
                    Optional.ofNullable(supTeamList).ifPresent(lists ->{
                        lists.stream().forEach(bean ->{
                            TUserInfo coreUser = userInfoMapper.selectTUserInfoByUserId(bean);
                            coreUser.setBalanceSum(coreUser.getBalanceSum().add(workSubsidy));
                            userInfoMapper.updateTUserInfo(coreUser);
                            log.info("-----------------购买终端确认收货，产生办公补贴------------------办公补贴分润人：" + coreUser.getUserId());
                            //写交易流水表(积分)
                            TUserDefaultInfo defaultInfoWork = commonUtils.generateTUserDefaultInfo(
                                    coreUser.getUserId(),
                                    order.getBrandId(),
                                    TransTypeEnum.YUE.getCode(),
                                    TransOperTypeEnum.YUE_1009.getCode(),
                                    workSubsidy,
                                    order.getId(),
                                    order.getUserId(),
                                    null,
                                    "",
                                    null);
                            userDefaultInfoMapper.insertTUserDefaultInfo(defaultInfoWork);
                        });
                    });
                }
            }
        }
        orderInfoMapper.updateTOrderInfo(order);
    }
}
